package com.lglin.common.config.security.service;

import com.lglin.bean.role.Role;
import com.lglin.bean.user.entity.SelfUserDetail;
import com.lglin.bean.user.entity.User;
import com.lglin.bean.user.entity.UserRole;
import com.lglin.common.config.exception.SelfException;
import com.lglin.common.utils.reponse.ResultEnum;
import com.lglin.service.role.RoleService;
import com.lglin.service.user.UserRoleService;
import com.lglin.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class SelfUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        SelfUserDetail userDetail = new SelfUserDetail();
        User user = userService.selectByEmail(email);
        if (user == null) {
            throw new SelfException(ResultEnum.Email_NotFound);
        }
        List<UserRole> userRoles = userRoleService.listByUserId(user.getId());
        for (UserRole userRole : userRoles) {
            Role role = roleService.selectById(userRole.getRid());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        userDetail.setEmail(user.getEmail());
        userDetail.setId(user.getId());
        userDetail.setPassword(user.getPassword());
        userDetail.setNickname(user.getNickname());
        userDetail.setAuthorities(authorities);
        return userDetail;
    }
}
